import pyautogui
import time
import threading
from collections import deque
from utils.config_loader import cfg

class GameController:
    def __init__(self):

        # 节流控制参数
        self.action_history = deque(maxlen=10)
        self.min_action_interval = 0.5  # 最小动作间隔(秒)
        
        # Load key mappings
        self.key_mappings = {
            'punch': cfg['KeyMappings']['punch'],
            'kick': cfg['KeyMappings']['kick'],
            'forward': cfg['KeyMappings']['forward'],
            'squat': cfg['KeyMappings']['squat'],
            'jump': cfg['KeyMappings']['jump'],
            'kamehameha': cfg['KeyMappings']['kamehameha']
        }
        print(f"[DEBUG] Key mappings loaded: {self.key_mappings}")
        
    def map_pose_to_action(self, pose_results):
        actions = []
        if pose_results.get('is_punch', False):
            actions.append('punch')
        if pose_results.get('is_kick', False):
            actions.append('kick')
        if pose_results.get('is_forward', False):
            actions.append('forward')
        if pose_results.get('is_squat', False):
            actions.append('squat')
        if pose_results.get('is_jump', False):
            actions.append('jump')
        if pose_results.get('is_kamehameha', False):
            actions.append('kamehameha')
        return actions
    
    def execute_action(self, action):
        def _execute():
            if action in self.key_mappings:
                print(f"[DEBUG] Executing action: {action} with key {self.key_mappings[action]}")
                key = self.key_mappings.get(action)
                # if action == 'forward':
                #     pyautogui.keyDown(key)
                #     time.sleep(1)
                #     pyautogui.keyUp(key)
                # else:
                #     pyautogui.press(key)
        threading.Thread(target=_execute).start()
            
    def check_and_execute(self, pose_results):
        actions = self.map_pose_to_action(pose_results)
        current_time = time.time()
        
        # 节流控制：检查上次同类型动作时间
        for action in actions:
            if len(self.action_history) > 0 and \
               (current_time - self.action_history[-1]) < self.min_action_interval:
                # print(f"[DEBUG] 动作 {action} 被节流控制忽略")
                continue
                
            self.execute_action(action)
            self.action_history.append(current_time)